<?php
// no direct access
defined( '_JEXEC' ) or die( 'Restricted access' );

$db =& JFactory::getDBO();

// Our Joomla! Version
$jversion = new JVersion();
$j15 = ($jversion->RELEASE == '1.5');


$mainframe = JFactory::getApplication();

if (!function_exists('MySendMail')) {
  if (file_exists('administrator/components/com_nspro/lib.php')) {
    include('administrator/components/com_nspro/lib.php');
  }
  else {
    print 'Please install the NS Pro component! (com_nspro.zip)';
    return false;
  }
}

// email parameters
$recipient = $params->get('email_recipient', 'email@email.com');
$subject = $params->get('subject', 'New subscription to your site!');
$fromName = $params->get('from_name', 'Newsletter Subscriber');
$fromEmail = $params->get('from_email', 'newsletter_subscriber@yoursite.com');

if ($fromName == 'Newsletter Subscriber') {
  $fromName = $mainframe->getCfg('fromname');
}
if ($fromEmail == 'newsletter_subscriber@yoursite.com') {
  $fromEmail = $mainframe->getCfg('mailfrom');
}

$sendingWithSetEmail = $params->get('sending_from_set', true);

// text parameters
$myNameLabel = $params->get('name_label', 'Name:');
$myEmailLabel = $params->get('email_label', 'Email:');
$mailing_list_label = $params->get('mailing_list_label', 'Mailing Lists:');
$buttonText = $params->get('button_text', 'Subscribe to Newsletter');
$pageText = $params->get('page_text', 'Thank you for subscribing to our site.');
$errorText = $params->get('errot_text', 'Your subscription could not be submitted. Please try again.');
$noName = $params->get('no_name', 'Please write your name');
$noEmail = $params->get('no_email', 'Please write your email');
$invalidEmail = $params->get('invalid_email', 'Please write a valid email');
$pre_text = $params->get('pre_text', '');

// size & color parameters
$nameWidth = $params->get('name_width', '20');
$emailWidth = $params->get('email_width', '20');
$buttonWidth = $params->get('button_width', '100');
$thanksTextColor = $params->get('thank_text_color', '#FF0000');
$errorTextColor = $params->get('error_text_color', '#FF0000');
$form_layout = $params->get('form_layout', '0');
$label_pos = $params->get('label_pos', '0');

// file parameters
$saveList = $params->get('save_list', true);
$savePath = $params->get('save_path', 'mailing_list.txt');
$saveFormat = $params->get('save_format', '%n (%e);');

// url parameters
$exact_url = $params->get('exact_url', true);
$disable_https = $params->get('disable_https', false);
$fixed_url = $params->get('fixed_url', true);
$myFixedURL = $params->get('fixed_url_address', "");

// anti spam parameters
$enable_anti_spam = $params->get('enable_anti_spam', true);
$myAntiSpamQuestion = $params->get('anti_spam_q', 'How many eyes has a typical person? (ex: 1)');
$myAntiSpamAnswer = $params->get('anti_spam_a', '2');
$anti_spam_position = $params->get('anti_spam_position', 0);

// multiple list parameters
$show_select_list = $params->get('show_select_list', 2);
$fixed_ids = $params->get('fixed_ids', '');

// extra field parameters
$field_list = $params->get('field_list', "0");
$fixed_fields = $params->get('fixed_field_ids', "");
$text_field_width = $params->get('text_field_width', "20");
$textarea_field_rows = $params->get('textarea_field_rows', "3");
$textarea_field_cols = $params->get('textarea_field_cols', "25");
$swidth = $params->get('select_field_width', '135');

// extra field constant
$name_prefix = 'mp_'; // for the module

// module class suffix
$moduleclass_sfx = $params->get('moduleclass_sfx');

/// C O M P O N E N T   P A R A M E T E R S
jimport('joomla.application.component.helper');
if ($j15 == true) {  
  $cparams = JComponentHelper::getParams( 'com_nspro' );
  $component = JComponentHelper::getComponent( 'com_nspro' );
  $cparams = new JParameter( $component->params );
  // We're in Joomla 1.5 (hurray!)
  $blacklist = $cparams->get('blacklist', '');
  $confirmSub = $cparams->get( 'send_confirm', '1');
  $fromNameConfirm = $cparams->get('from_name_confirm', 'Newsletter Subscriber');
  $fromEmailConfirm = $cparams->get('from_email_confirm', 'newsletter_subscriber@yoursite.com');

  if ($fromNameConfirm == 'Newsletter Subscriber') {
    $fromNameConfirm = $mainframe->getCfg('fromname');
  }
  if ($fromEmailConfirm == 'newsletter_subscriber@yoursite.com') {
    $fromEmailConfirm = $mainframe->getCfg('mailfrom');
  }

  $subjectConfirm = $cparams->get('subject_confirm', 'Subscription Confirmation');
  $messageConfirm = $cparams->get('message_confirm', 'Thank you for subscribing at {conf_host} .<br/><br/><br/>{conf_link}Click to complete your Subscription{/conf_link}<br/><br/>or copy this to your address bar<br/><br/>{conf_url}');

  $subjectConfirm = JText::_($subjectConfirm);
  $messageConfirm = JText::_($messageConfirm);
}
else {
  $cparams =& JComponentHelper::getParams('com_nspro');
  // We're in Joomla 1.6
  $blacklist = $cparams->getValue('data.params.blacklist', '');
  $confirmSub = $cparams->getValue('data.params.send_confirm', '1');
  $fromNameConfirm = $cparams->getValue('data.params.from_name_confirm', 'Newsletter Subscriber');
  $fromEmailConfirm = $cparams->getValue('data.params.from_email_confirm', 'newsletter_subscriber@yoursite.com');

  if ($fromNameConfirm == 'Newsletter Subscriber') {
    $fromNameConfirm = $mainframe->getCfg('fromname');
  }
  if ($fromEmailConfirm == 'newsletter_subscriber@yoursite.com') {
    $fromEmailConfirm = $mainframe->getCfg('mailfrom');
  }

  $subjectConfirm = $cparams->getValue('data.params.subject_confirm', 'Subscription Confirmation');
  $messageConfirm = $cparams->getValue('data.params.message_confirm', 'Thank you for subscribing at {conf_host} .<br/><br/><br/>{conf_link}Click to complete your Subscription{/conf_link}<br/><br/>or copy this to your address bar<br/><br/>{conf_url}');

  $subjectConfirm = JText::_($subjectConfirm);
  $messageConfirm = JText::_($messageConfirm);
}

$separator = '';
if ($form_layout === '0') {
  $br = '<br/>';
  $tr = '<tr>';
  $ctr = '</tr>';
  $td = '<td>';
  $tdcolspan = '<td colspan="2">';
  $ctd = '</td>';
  $table = '<table border="0" class="nsprotable">';
  $ctable = '</table>';
  $emptycell = '<td></td>';
	if ($j15 != true) {
		$tr = '<tr style="border: none;">';			
		$td = '<td style="border: none; padding: 2px;">';
		$tdcolspan = '<td colspan="2" style="border: none; padding: 2px;">';
		$emptycell = '<td style="border: none;"></td>';
	}  
  $separator = $ctd . $td;
  if ($label_pos == '1') {
    $separator = $br;
    $emptycell = '';
  }
}
else {
  $br = ' ';
  $tr = '';
  $ctr = '';
  $td = '<td>';
  $tdcolspan = '<td>';
  $ctd = '</td>';
  $table = '<table border="0" class="nsprotable"><tr>';
  if ($j15 != true) {
    $td = '<td style="border: none; padding: 2px;">';
    $tdcolspan = $td;
  }  
  $ctable = '</tr></table>';
  $emptycell = '';
  $separator = $ctd . $td;
}

// URL where we post
if ($fixed_url) {
  $url = $myFixedURL;
}
else {
  if (!$exact_url) {
    $url = JURI::current();
  }
  else {
    if (!$disable_https) {
      $url = (!empty($_SERVER['HTTPS'])) ? "https://".$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'] : "http://".$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'];
    }
    else {
      $url = "http://".$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'];
    }
  }
}

// Sanitize URL
$url = htmlentities($url, ENT_COMPAT, "UTF-8");


$myError = "";
$errors = 3;

if (isset($_POST["mp_name"])) {
  $errors = 0;
  if ($enable_anti_spam) {
    if ($_POST["modnsp_anti_spam_answer"] != $myAntiSpamAnswer) {
      $myError = '<span style="color: '.$errorTextColor.';">' . JText::_('Wrong anti-spam answer') . '</span>' . $br;
    }
  }
  if ($_POST["mp_name"] === "") {
    $myError = $myError . '<span style="color: '.$errorTextColor.';">' . $noName . '</span>' . $br;
    $errors = $errors + 1;
  }
  if ($_POST["mp_email"] === "") {
    $myError = $myError . '<span style="color: '.$errorTextColor.';">' . $noEmail . '</span>' . $br;
    $errors = $errors + 2;
  }
  if (($errors & 2) != 2) {
    if (!preg_match("/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$/", strtolower($_POST["mp_email"]))) {
      $myError = $myError . '<span style="color: '.$errorTextColor.';">' . $invalidEmail . '</span>' . $br;
      $errors = $errors + 2;
    }
  }

  if (($errors & 2) != 2) {

    $blackarray = explode(';', $blacklist);

    foreach ($blackarray as $black_email) {
      if ($_POST["mp_email"] == $black_email) {
        $myError = $myError. '<span style="color: '.$errorTextColor.';">' . JText::_('Your email has been blacklisted.') . '</span>' . $br;
        $errors = $errors + 2;
        break;
      }
    }
  }

  $vresult = ValidateExtraFields($_POST, true, $br, $errorTextColor, 'module');
  if ($vresult !== true) {
    $myError = $myError . $vresult;
  }

  if ($myError == "") {

    // if we don't use the confirmation process
    if (!$confirmSub) {
      $mailSender = &JFactory::getMailer();
      $mailSender->addRecipient($recipient);
      if ($sendingWithSetEmail) {
        $mailSender->setSender(array($fromEmail,$fromName));
      }
      else {
        $mailSender->setSender(array($_POST["mp_email"],$_POST["mp_name"]));
      }
      $mailSender->setSubject($subject);

      // insert into the database
      $mlists = '';
      if (isset($_POST["mailing_lists2"])) {
        $myposts = $_POST["mailing_lists2"];
        foreach($myposts as $mpost) {
          if ($mlists == '') {
            $mlists = $mpost;
          }
          else {
            $mlists = $mlists . ',' . $mpost;
          }
        }
      }
      else if (isset($_POST["mailing_lists"])) {
        $mlists = $_POST["mailing_lists"];
      }

      $myMessage = $myNameLabel . ' ' . htmlentities($_POST["mp_name"]) . ', ' .
                   $myEmailLabel . ' ' . htmlentities($_POST["mp_email"]) . ', ' .
                   date("r") . ', ' .
                   $mailing_list_label . ' ';
      $alllists = explode(',', $mlists);
      $myliststring = '';
      if (count($alllists) > 0) {
        foreach($alllists as $alist) {
          if ($alist != '') {
            $query = 'SELECT * FROM `#__nspro_lists` WHERE `published` = 1 and `id` = "' . mysql_escape_string($alist) . '"';
            $db->setQuery($query);
            $tlist = $db->loadObject();
            if ($myliststring == '') {
              $myliststring = $myliststring . $tlist->lname;
            }
            else {
              $myliststring = $myliststring . ', ' . $tlist->lname;
            }
          }
        }
      }
      $myMessage = $myMessage . $myliststring;

      $myMessage .= "\n" . ExtraFieldsToString('module', 0);

      $mailSender->setBody($myMessage);

      $query = 'INSERT INTO `#__nspro_subs` (`NAME`, `EMAIL`, `DATETIME`, `CONFIRMED`, `mailing_lists`) VALUES ("'.mysql_escape_string($_POST["mp_name"]).'", "'.mysql_escape_string($_POST["mp_email"]).'", "'.date("Y-m-d H:i:s").'", "1", "' .mysql_escape_string($mlists). '")';
      $db->setQuery($query);
      if (!$db->query()) {
        $myError = $myError . '<span style="color: '.$errorTextColor.';">' . JText::_('Email already exists. Please try again') . '</span>' . $br;
        $errors = $errors + 2;
      }
      else {
        // if inserted, save the extra fields.
        if ($vresult === true) {
          $saved = SaveExtraFields($db->insertid(), $_POST, true, 'module');
          if ($saved !== true) {
            print '<div class="modnspro' . $moduleclass_sfx . '"><span style="color: '.$errorTextColor.';">' . $saved . '</span></div>';
          }
        }
        // if inserted, send the mail
        if ($mailSender->Send() !== true) {
          $myReplacement = '<div class="modnspro' . $moduleclass_sfx . '"><span style="color: '.$errorTextColor.';">' . $errorText . '</span></div>';
          print $myReplacement;
        }
        else {
          $myReplacement = '<div class="modnspro' . $moduleclass_sfx . '"><span style="color: '.$thanksTextColor.';">' . $pageText . '</span></div>';
          print $myReplacement;
        }
        // save to the global list file
        if ($saveList) {
          $file = fopen($savePath, "a");
          if ($file !== false) {
            $mstring = JString::str_ireplace('%n', htmlentities($_POST["mp_name"]), $saveFormat);
            $mstring = JString::str_ireplace('%e', htmlentities($_POST["mp_email"]), $mstring);
            fwrite($file, $mstring);
            fclose($file);
          }
        }
      }

      if ($myError == '') {
        return true;
      }
    } // if we use the confirmation process
    else {
      $confirm_url = 'index.php?option=com_nspro&amp;view=nspro&amp;layout=confirm&amp;nss=nsm';
      $uri = & JURI::getInstance();
      $myBase = JURI::base();

      $myConfirmationLink = $myBase.$confirm_url.'&amp;u='.md5($_POST["mp_email"]);

      $myMessage = str_replace('{conf_host}', $uri->getHost(), $messageConfirm);
      $myMessage = str_replace('{conf_url}', $myConfirmationLink, $myMessage);

      $myMessage = str_replace('{conf_link}', '<a href="' . $myConfirmationLink . '">', $myMessage);
      $myMessage = str_replace('{/conf_link}', '</a>', $myMessage);

      // insert into the database, to be able to confirm
      $mlists = '';
      if (isset($_POST["mailing_lists2"])) {
        $myposts = $_POST["mailing_lists2"];
        foreach($myposts as $mpost) {
          if ($mlists == '') {
            $mlists = $mpost;
          }
          else {
            $mlists = $mlists . ',' . $mpost;
          }
        }
      }
      else if (isset($_POST["mailing_lists"])) {
        $mlists = $_POST["mailing_lists"];
      }
      $query = 'INSERT INTO `#__nspro_subs` (`NAME`, `EMAIL`, `DATETIME`, `CONFIRMED`, `mailing_lists`) VALUES ("'.mysql_escape_string($_POST["mp_name"]).'", "'.mysql_escape_string($_POST["mp_email"]).'", "'.date("Y-m-d H:i:s").'", "0", "'.mysql_escape_string($mlists).'")';
      $db->setQuery($query);
      if (!$db->query()) {
        $myError = $myError . '<span style="color: '.$errorTextColor.';">' . JText::_('Email already exists. Please try again') . '</span>' . $br;
        $errors = $errors + 2;
      }
      else {
        if ($vresult === true) {
          $saved = SaveExtraFields($db->insertid(), $_POST, true, 'module');
          if ($saved !== true) {
            print '<div class="modnspro' . $moduleclass_sfx . '"><span style="color: '.$errorTextColor.';">' . $saved . '</span></div>';
          }
        }
        if (MySendMail($fromEmailConfirm, $fromNameConfirm, $_POST["mp_email"], $subjectConfirm, $myMessage, true) !== true) {
          $myReplacement = '<span style="color: '.$errorTextColor.';">' . JText::_('Your subscription could not be completed') . '</span>';
        }
        else {
          $myReplacement = '<span style="color: '.$thanksTextColor.';">' . JText::_('An email has been sent to you to confirm your subscription') . '</span>';
        }
        print '<div class="modnspro' . $moduleclass_sfx . '">'. $myReplacement . '</div>';
        return true;
      }

      if ($myError == '') {
        return true;
      }
    }
  }
}


if ($recipient === "") {
  $myReplacement = '<span style="color: '.$errorTextColor.';">'.JText::_('No recipient specified').'</span>';
  print $myReplacement;
  return true;
}

if ($recipient === "email@email.com") {
  $myReplacement = '<span style="color: '.$errorTextColor.';">'.JText::_('Mail Recipient is specified as email@email.com.').'<br/>'.JText::_('Please change it from the Module parameters.').'</span>';
  print $myReplacement;
  return true;
}

if ($myError != "") {
  print $myError;
}

$db->setQuery('SELECT * FROM `#__nspro_fields` WHERE `published` = true');
$afields = $db->loadObjectList();

print '<div class="modnspro' . $moduleclass_sfx . '"><form action="' . $url . '" method="post">' . "\n".
      '<div class="modnsprointro' . $moduleclass_sfx . '">'.$pre_text.'</div>' . "\n";
print $table;
if ($enable_anti_spam) {
  if ($anti_spam_position == 0) {
    print $tr . $tdcolspan . $myAntiSpamQuestion . $ctd . $ctr . $tr . $emptycell . $td . '<input class="modnspro inputbox ' . $moduleclass_sfx . '" type="text" name="modnsp_anti_spam_answer" size="' . $nameWidth . '"/>' . $ctd . $ctr . "\n";
  }
}
// extra fields before form
foreach($afields as $afield) {
  if (!$afield->abovepos) {
    continue;
  }
  if ($field_list == '1') {
    $fieldarray = explode(',', $fixed_fields);
    if (!in_array($afield->id, $fieldarray)) {
      continue;
    }
  }
  $val = '';
  if ($afield->fieldtype != '7') {
    print $tr . $td;
    print JText::_($afield->name);
    print $separator;
    if (isset($_POST[$name_prefix.'field'.$afield->id])) {
      if (!FieldHadError($vresult, $afield->name)) {
        $val = $_POST[$name_prefix.'field'.$afield->id];
      }
    }
  }
  $fieldinput = GetFieldInputModulePlugin($afield, $val, $moduleclass_sfx, 'module', $text_field_width, $textarea_field_rows, $textarea_field_cols, $swidth);
  print $fieldinput;
  if ($afield->fieldtype != '7') {
    print $ctd . $ctr;
  }
}
print $tr . $td . $myNameLabel . $separator . '<input class="modnspro inputbox' . $moduleclass_sfx . '" type="text" name="mp_name" maxlength="100" size="' . $nameWidth . '"';
if (($errors & 1) != 1) {
  print ' value="'.htmlentities($_POST["mp_name"]).'"';
}
print '/>' . $ctd . $ctr . "\n";
print $tr . $td . $myEmailLabel . $separator . '<input class="modnspro inputbox' . $moduleclass_sfx . '" type="text" name="mp_email" maxlength="200" size="' . $emailWidth . '"';
if (($errors & 2) != 2) {
  print ' value="'.htmlentities($_POST["mp_email"]).'"';
}
print '/>' . $ctd . $ctr . "\n";

if ($show_select_list == 0) {
  print '<input type="hidden" name="mailing_lists" value="' . $fixed_ids . '"/>';
}
else {
  $query = 'SELECT * FROM `#__nspro_lists` WHERE `published` = 1 ORDER BY `id`';
  $db->setQuery($query);
  $lists = $db->loadObjectList();

  if (count($lists) > 0) {
    print $tr . $tdcolspan . $mailing_list_label . $ctd . $ctr;
    if ($show_select_list == 1) {
      $fixedlist = explode(',', $fixed_ids);
      foreach($lists as $list) {
        foreach($fixedlist as $fxlid) {
          if ($list->id == $fxlid) {
            print $tr . $tdcolspan . '<input class="modnspro inputbox' . $moduleclass_sfx . '" type="checkbox" name="mailing_lists2[]" value="' . $list->id . '"/> ' . $list->lname . $ctd . $ctr;
          }
        }
      }
    }
    else {
      foreach($lists as $list) {
        print $tr . $tdcolspan . '<input class="modnspro inputbox' . $moduleclass_sfx . '" type="checkbox" name="mailing_lists2[]" value="' . $list->id . '"/> ' . $list->lname . $ctd . $ctr;
      }
    }
  }
}

// extra fields after form
foreach($afields as $afield) {
  if ($afield->abovepos) {
    continue;
  }
  if ($field_list == '1') {
    $fieldarray = explode(',', $fixed_fields);
    if (!in_array($afield->id, $fieldarray)) {
      continue;
    }
  }
  $val = '';
  if ($afield->fieldtype != '7') {
    print $tr . $td;
    print JText::_($afield->name);
    print $separator;
    if (isset($_POST[$name_prefix.'field'.$afield->id])) {
      if (!FieldHadError($vresult, $afield->name)) {
        $val = $_POST[$name_prefix.'field'.$afield->id];
      }
    }
  }
  $fieldinput = GetFieldInputModulePlugin($afield, $val, $moduleclass_sfx, 'module', $text_field_width, $textarea_field_rows, $textarea_field_cols, $swidth);
  print $fieldinput;
  if ($afield->fieldtype != '7') {
    print $ctd . $ctr;
  }
}

if ($enable_anti_spam) {
  if ($anti_spam_position == 1) {
    print $tr . $tdcolspan . $myAntiSpamQuestion . $ctd . $ctr . $tr . $emptycell . $td . '<input class="modnspro inputbox ' . $moduleclass_sfx . '" type="text" name="modnsp_anti_spam_answer" size="' . $nameWidth . '"/>' . $ctd . $ctr . "\n";
  }
}
print $tr . $tdcolspan . '<input class="modnspro button' . $moduleclass_sfx . '" type="submit" value="' . $buttonText . '" style="width: ' . $buttonWidth . '%"/>'. $ctd . $ctr . $ctable . '</form></div>' . "\n";
return true;
